package org.ResearchProject.interruptors;



import com.fasterxml.jackson.databind.ObjectMapper;
import org.ResearchProject.utils.JwtUtil;
import org.ResearchProject.utils.ThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


@Component
public class LoginInterceptor implements HandlerInterceptor {
    private final ObjectMapper objectMapper = new ObjectMapper(); // 创建 ObjectMapper 实例

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       try {
           String token = request.getHeader("token");
           Map<String, Object> message = JwtUtil.parseToken(token);
           System.out.println(message.toString());
           ThreadLocalUtil.set(message); // 每个用户都会创建一个线程， 为 ThreadLocal 相当于公共保险柜 存储用户信息 不会乱来
           // 放行
           return true;
       }catch (Exception e){
           response.setStatus(401);
           // 创建错误信息的 JSON 对象
           Map<String, String> errorResponse = new HashMap<>();
           errorResponse.put("error", "user did not login in!");
           errorResponse.put("message", e.getMessage());
           // 将 JSON 对象写入响应体
           response.getWriter().write(objectMapper.writeValueAsString(errorResponse));
           return false;
       }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //  请求结束，清空线程变量
        ThreadLocalUtil.remove();
    }
}
